import React from 'react';
import { connect } from 'dva'
import moment from 'moment'

import Title from 'components/Title'
import Chart from 'components/Chart'
import Tools from 'utils/tools';

import styles from './style/Statistics.less'

import { config } from 'utils'
const { scada } = config;
const {
  StationIds
} = scada;
const {
  source,
} = StationIds;

@connect(({ production }) => ({ ...production }))
class Statistics extends React.Component {
  echartsConf = [
    {
      key: 'ysl',
      label: '源水量',
      chart: {
        type: 'Common2',
        columns: {
          seriesItems: [
            // { name: '环比', field: 'sourceR', type: 'line', yAxisIndex: 1 },
            // { name: '同比', field: 'sourceT', type: 'line' },
            { name: '源水量', field: 'source', type: 'bar', barWidth: '25%' }
          ],
          yAxis: [{ name: '万m³' }],
        },
        color: ['78, 203, 115', '251, 212, 55', '68, 130, 255', '134, 147, 243'],
        other: { showLegend: true },
      },
      server: { type: 'production/querySource', payload: {} }
    },
    {
      key: 'gsl',
      label: '供水量',
      chart: {
        type: 'Common2',
        columns: {
          seriesItems: [
            // { name: '环比', field: 'supplyR', type: 'line', yAxisIndex: 1 },
            // { name: '同比', field: 'supplyT', type: 'line' },
            { name: '供水量', field: 'supply', type: 'bar', barWidth: '25%' }
          ],
          yAxis: [{ name: '万m³' }],
        },
        color: ['78, 203, 115', '251, 212, 55', '68, 130, 255', '134, 147, 243'],
        other: { showLegend: true },
      },
      server: { type: 'production/querySupply', payload: {} }
    },
  ]

  constructor(props) {
    super(props);

    let time;
    if ('defaultValue' in props) {
      time = props.defaultValue;
    }

    this.state = {
      time,
      index: 0,
      param: {},
      monthList: [],
      lastYearMonthList: []
    }
  }

  componentDidMount() {
    const { echartsConf, state } = this;
    const { index } = state;
    this.setState({
      param: echartsConf[index]
    }, () => {
      this.init();
    })
  }

  init = async () => {
    await this.setDateECharts()
  }

  componentWillReceiveProps(nextProps) {
    if (this.props.defaultValue !== nextProps.defaultValue) {
      if (nextProps.defaultValue) {
        this.setState({
          time: nextProps.defaultValue
        }, () => {
          this.init()
        })
      }
    }
  }

  // 获取指标
  setDateECharts = () => {
    // const { time, param } = this.state;
    // const { server, key } = param;
    // let { payload, type } = server;
    //
    // // 公共参数
    // Object.assign(payload, {
    //   Token,
    //   DTypes: ["SJLJ"],
    //   Interval: 86400,
    //   Begin: moment(`${time}-01-01 00:00:00`).unix(),
    //   End: moment(`${time}-12-31 23:59:59`).unix(),
    // })
    // // 源水量
    // if (key === 'ysl') {
    //   source.forEach((StationId, idx) => {
    //     const payloads = Object.assign({}, payload, {
    //       StationId,
    //       type: `_${idx}`
    //     })
    //     this.queryServer({ type, payload: payloads })
    //   })
    //   // 供水量
    // } else if (key === 'gsl') {
    //   Object.assign(payload, { StationId: supply[0], type: 2 })
    //   this.queryServer(server, { payload })
    // }
  }

  queryServer = async (server) => {
    console.log(server, 120)
    await this.props.dispatch(server);
  }

  // change
  handleChange = (param, index) => {
    const lastIndex = this.state.index;
    if (lastIndex === index) {
      return;
    }
    this.setState({
      index,
      param,
    }, async () => {
      await this.setDateECharts()
    })
  }

  // 渲染Tab
  RenderTabs = () => {
    const { echartsConf, state } = this;
    const { index } = state;

    let Tabs = null;
    Tabs = echartsConf.map((tab, idx) => {
      const activedCls = index === idx ? styles.actived : '';
      return (<div key={idx}
        className={`${styles.tab} ${activedCls}`}
        onClick={this.handleChange.bind(this, tab, idx)}
      >
        {tab.label}
      </div>)
    })
    return (<div style={{ textAlign: "center" }}>
      <div className={styles.Tabs}>{Tabs}</div>
    </div>);
  }
  // 图表渲染
  RenderECharts = () => {

    const { param } = this.state;
    if (!param.chart) return false;
    const { time } = this.state;
    const monthList = Tools.getFullMonth(time);
    const lastYearMonthList = Tools.getFullMonth(time-1);

    let resource = {
      source: [], sourceT: [], sourceR: [],  //源水，源水同比，源水环比
      supply: [], supplyT: [], supplyR: [], sourceSupplyPrec: [], unUsedSource: [], //供水水，供水同比，供水环比，源水利用率
      drugNaClO3: [], drugHCL: [], electric: [], //氯酸钠，盐酸 ,用电量
      electric_cost:[],drug_cost:[],supply_cost:[]} //电费，药费，一吨水成本
    let times = []

    //封装上一年的源水和供水数据
    let lastYearMonthSourceVals = {};
    let lastYearMonthSupplyVals = {};
    let lastMonthSourceVal = 0;
    let lastMonthSupplyVal = 0;
    lastYearMonthList.forEach(ele => {
      // 每月第一天 和 最后一天
      const startTimestamp = moment(moment(ele).startOf('month')).unix();
      const endTimestamp = moment(moment(ele).endOf('month')).unix();

      const months = moment(ele).month();
      let sourceSum = 0,supplySum = 0;
      source.forEach((item, idx) => {
        const resouseVals = this.props[`SourceResourc3${idx}`] && this.props[`SourceResource3${idx}`][0] && this.props[`SourceResource3${idx}`][0].Vals
          ? this.props[`SourceResource3${idx}`][0].Vals : [];
        resouseVals.forEach(term => {
          const {Time, Report} = term;
          const {maxv} = Report;
          if(Time >= startTimestamp && Time <= endTimestamp ){
            sourceSum += maxv
          }
        })
      })
      lastYearMonthSourceVals[months] = sourceSum;
      lastMonthSourceVal = sourceSum;
      const supplyVals = this.props["SupplyResource3"] && this.props["SupplyResource3"][0] && this.props["SupplyResource3"][0].Vals
        ? this.props["SupplyResource3"][0].Vals : [];
      supplyVals.forEach(term => {
          const { Time,Report } = term;
          const { maxv } = Report;
          if(Time >= startTimestamp && Time <= endTimestamp ){
            supplySum += maxv
          }
        }
      )
      lastYearMonthSupplyVals[months] = supplySum;
      lastMonthSupplyVal = supplySum;
    })

    monthList.forEach(ele => {
      // 每月第一天 和 最后一天
      const startTimestamp = moment(moment(ele).startOf('month')).unix();
      const endTimestamp = moment(moment(ele).endOf('month')).unix();
      const months = moment(ele).month();
      // 处理时间
      times.push(moment(ele).format('M月'))
      //获取源水量
      let sourceSum = 0;
      source.forEach((item, idx) => {
        const resouseVals = this.props[`SourceResource2${idx}`] && this.props[`SourceResource2${idx}`][0] && this.props[`SourceResource2${idx}`][0].Vals
          ? this.props[`SourceResource2${idx}`][0].Vals : [];
        resouseVals.forEach(term => {
          const {Time, Report} = term;
          const {maxv} = Report;
          if(Time >= startTimestamp && Time <= endTimestamp ){
            sourceSum += maxv
          }
        })
      })
      resource.source.push((sourceSum/10000).toFixed(2));
      resource.sourceT.push(lastYearMonthSourceVals[months] ? ((sourceSum-lastYearMonthSourceVals[months])*100.0/lastYearMonthSourceVals[months]).toFixed(1) : 0);
      resource.sourceR.push(lastMonthSourceVal ? ((sourceSum-lastMonthSourceVal)*100.0/lastMonthSourceVal).toFixed(1): 0);
      lastMonthSourceVal = sourceSum;
      //获取供水量
      let supplySum = 0;
      const supplyVals = this.props["SupplyResource2"] && this.props["SupplyResource2"][0] && this.props["SupplyResource2"][0].Vals
        ? this.props["SupplyResource2"][0].Vals : [];
      supplyVals.forEach(term => {
          const { Time,Report } = term;
          const { maxv } = Report;
          if(Time >= startTimestamp && Time <= endTimestamp ){
            supplySum += maxv
          }
        }
      )
      resource.supply.push((supplySum/10000).toFixed(2));
      resource.supplyT.push(lastYearMonthSupplyVals[months] ? ((supplySum-lastYearMonthSupplyVals[months])*100.0/lastYearMonthSupplyVals[months]).toFixed(1) : 0);
      resource.supplyR.push(lastMonthSupplyVal ? ((supplySum-lastMonthSupplyVal)*100.0/lastMonthSupplyVal).toFixed(1): 0);
      resource.unUsedSource.push(((sourceSum-supplySum)/10000).toFixed(2));
      resource.sourceSupplyPrec.push(sourceSum ? (supplySum*100.0/sourceSum).toFixed(1) : 0)
      lastMonthSupplyVal = supplySum;
    })


    const { chart } = param;
    const { type: chartType, columns, color, other } = chart;
    const dataSource = {};
    columns['seriesItems'].forEach(ele => {
      const { field } = ele;
      Object.assign(ele, { data: resource[field]})
    })

    Object.assign(dataSource, { time: times, data: columns['seriesItems'] })

    return (
      <Chart
        type={chartType}
        color={color}
        columns={columns}
        dataSource={dataSource}
        other={other}
      />)
  }

  render() {
    return (<Title title={'水量分析'}>
      {this.RenderTabs()}
      {this.RenderECharts()}
    </Title>)
  }
}

export default Statistics;
